package com.boyunv.strategy.example03;
/*
 *@description
 * 策略工厂类
 *@author boyunv
 *@create 2023/8/15 7:38
 *@version 1.0
 */

import com.boyunv.strategy.example02.Receipt;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import javax.xml.parsers.SAXParser;
import java.util.HashMap;
import java.util.Map;

public class ReceiptHandleStrategyFactory {
    public ReceiptHandleStrategyFactory(){
        
    }
    //使用MAP集合存储策略信息,彻底消除if  ...else
    private  static Map<String,ReceiptHandlerStrategy> strategyMap;
    //初始化具体的策略,保存到map集合
    public  static void  init(){
        strategyMap= new HashMap<>();
//        strategyMap.put("MT1101",new MT1101HandlerStrategy());
//        strategyMap.put("MT1102",new MT1102HandlerStrategy());
//        strategyMap.put("MT1103",new MT1103HandlerStrategy());
        try {
            SAXReader reader=new SAXReader();
            String file="D:\\projs\\design-patterns\\byv-strategy-patttern-14\\src\\main\\resources\\config.xml";
            Document read = reader.read(file);
            Node node = read.selectSingleNode("/config/className");
            String className = node.getText();
            Class clazz= Class.forName(className);
            ReceiptHandlerStrategy receiptHandlerStrategy = (ReceiptHandlerStrategy) clazz.newInstance();
            strategyMap.put("MT1101",receiptHandlerStrategy);
            
            
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    
    //根据回执类型,获取对应的策略对象
    public  static   ReceiptHandlerStrategy getStrategy(String receiptType){
        return strategyMap.get(receiptType);
    }
}

